@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: ================ 初始化 ================
cls
echo.
echo ╔══════════════════════════════════════════╗
echo ║          文件替换工具（HTML版）          ║
echo ╚══════════════════════════════════════════╝
echo.

:: ================ 用户输入目标字符串 ================
:input_target
set "target_str="
set /p "target_str=请输入要查找替换的目标字符串: "
if "!target_str!"=="" (
    echo 错误：输入不能为空！
    goto input_target
)

:: ================ 检查替换文件 ================
if not exist "fq.txt" (
    echo 错误：未找到替换内容文件 fq.txt
    pause
    exit /b
)

:: ================ 文件扫描 ================
echo.
echo 正在扫描所有子目录中的 *.html 文件...
set file_count=0
for /r %%f in (*.html) do (
    findstr /i /m /c:"!target_str!" "%%f" >nul
    if !errorlevel! equ 0 (
        set /a file_count+=1
        set "file_!file_count!=%%~ff"
        echo [!file_count!] %%f
    )
)

:: ================ 扫描结果 ================
echo.
echo ================ 扫描结果 ================
if !file_count! equ 0 (
    echo 未找到包含字符串 "!target_str!" 的文件
    pause
    exit /b
)
echo 共发现 !file_count! 个文件需要替换
echo.

:: ================ 用户确认 ================
:confirm
set "choice="
set /p "choice=是否执行替换？(Y=确认执行/N=取消): "
if /i "!choice!"=="Y" goto do_replace
if /i "!choice!"=="N" exit /b
goto confirm

:: ================ 执行替换 ================
:do_replace
echo.
echo 正在读取替换内容文件...
set line_num=0

for /f "delims=" %%a in (fq.txt) do (
    set /a line_num+=1
    set "replace_!line_num!=%%a"
    if !line_num! leq !file_count! (
        echo [内容!line_num!] %%a
    )
)

if !line_num! lss !file_count! (
    echo.
    echo 错误：fq.txt 只有 !line_num! 行内容，但需要替换 !file_count! 个文件！
    pause
    exit /b
)

echo.
echo ================ 开始替换 ================
set success_count=0
for /l %%i in (1,1,!file_count!) do (
    set "current_file=!file_%%i!"
    set "new_content=!replace_%%i!"
    
    echo.
    echo ■ 正在处理：!current_file!
    echo ■ 替换内容：!new_content!
    
    :: 使用PowerShell进行UTF-8编码的替换操作
    powershell -Command "$content=Get-Content -Path '!current_file!' -Raw -Encoding Utf8; $content -replace [regex]::Escape('!target_str!'), '!new_content!' | Set-Content -Path '!current_file!' -Encoding Utf8"
    
    if !errorlevel! equ 0 (
        echo ■ 状态：成功
        set /a success_count+=1
    ) else (
        echo ■ 状态：失败
    )
)

:: ================ 最终报告 ================
echo.
echo ================ 替换完成 ================
echo 目标字符串：!target_str!
echo 成功替换：!success_count!/!file_count! 个文件
echo.

pause